package com.squirrel.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description 集成swagger
 * @Author 关远键
 * @Version v1.0.0
 * @Date 2021/11/7 16:17
 */
@Configuration
@EnableOpenApi
public class SwaggerConfig {
    @Bean
    public Docket docket(Environment environment) {
        //设置要显示swagger的环境
        Profiles of = Profiles.of("dev", "test");
        //判断当前是否处于该环境
        boolean b = environment.acceptsProfiles(of);

        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .enable(b)
                .securityContexts(Arrays.asList(securityContext()))
                .securitySchemes(Arrays.asList(apiKey()))
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.squirrel.common.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 配置文档信息
     * @author 关远键
     * @date 2021/11/7 16:30
     * @return null
     */
    private ApiInfo apiInfo() {
        Contact contact = new Contact("关远键", "https://gitee.com/gyjian/squirrel-java.git", "3427916511@qq.com");
        return new ApiInfo("松鼠视频接口文档",
                "简单的接口文档",
                "v1.0",
                "https://gitee.com/gyjian/squirrel-java.git",
                contact,
                "官方许可",
                "https://www.baidu.com",
                new ArrayList()
        );
    }


    /**
     * 配置 全局 token 认证
     *
     * @return
     */
    private ApiKey apiKey() {
        return new ApiKey("JWT", "Authorization", "header");
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder().securityReferences(defaultAuth()).build();
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Arrays.asList(new SecurityReference("JWT", authorizationScopes));
    }
}
